package com.zkx.laolaiyi.utils;

import com.baomidou.mybatisplus.core.toolkit.AES;
import com.zkx.laolaiyi.properties.PrivateKeyProperties;
import io.jsonwebtoken.security.Keys;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;

/**
 * 加密工具类
 * 把私钥变为一个SecretKey，供Jwt使用
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class EncryptUtil {
    private static final String fieldKey = "13SHzkxMN9Love14";

    public static SecretKey createSecretKey(String secretKey) {
        try {
            MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
            byte[] bytes = sha256.digest(secretKey.getBytes(StandardCharsets.UTF_8));
            return Keys.hmacShaKeyFor(bytes);
//            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
//            byte[] passwordBytes = secretKey.getBytes(StandardCharsets.UTF_8);
//            DESKeySpec desKeySpec = new DESKeySpec(passwordBytes);
//            return keyFactory.generateSecret(desKeySpec);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static String autoEncryptStringField(String fieldValue) {
        return Base64.getEncoder().encodeToString(
                AES.encrypt(fieldValue, fieldKey).getBytes(StandardCharsets.UTF_8)
        );
    }

    public static String autoDecryptStringField(String fieldValue) {
        return AES.decrypt(
                new String(Base64.getDecoder().decode(fieldValue), StandardCharsets.UTF_8), fieldKey
        );
    }
}
